/**
 * @author kobe
 * @date   16/05/31
 */

import PullRefresh from '../components/mui/PullRefresh.js';
import NoData from '../components/NoData.js';
import {health} from "../const/offices";
import {prefix} from "../const/prefix";

(function (lf, r) {
    var RC = r.createClass,
        ajax = lf.utils.ajax,
        api = health.api,
        apiUrl = prefix.oldpeople,
        doAction = lf.bridgeJs.doAction,
        setTitle = lf.bridgeJs.setTitle,
        dataId,
        flag = lf.utils.getUrlParam('flag');

    const FINGER = 'finger';

    //test
    var NoticeList = RC({
        componentDidMount: function () {
        },
        render: function () {
            var user = this.props.user,
                houseNum = this.props.houseNum,
                noData = this.props.noData;
            var notice_list = this.props.info.map(function (info) {
                return (
                    <List info={info} noticeId={info.id} user={user} houseNum={houseNum}/>
                )
            })
            if (noData) {
                var noData = {
                    span_text: '您的报事列表为空',
                };
                return <NoData data={noData}/>
            } else {
                return (
                    <ul className="mui-table-view mui-table-view-striped mui-table-view-condensed">
                        {notice_list}
                    </ul>
                )
            }

        }
    })

    var List = RC({
        componentDidMount: function () {
            var $toDetail = r.findDOMNode(this.refs.toDetail),
                $consult = r.findDOMNode(this.refs.consult),
                $evaluation = r.findDOMNode(this.refs.evaluation),
                me = this;

            var eventId = this.props.info.id,
                wfOrderId = this.props.info.wfOrderId,
                staffId = this.props.info.staffId;

            // $(toDetail).on('tap',function () {
            //     var pageNum =  parseInt($(this).parent('li').index()) + 1;
            //     doAction('report-history-detail.html?flag=finger&page=' + pageNum + '&houseNum=' + me.props.houseNum, '报事详情')
            // });

            //报事列表点击运行函数
            $($toDetail).on('tap', function (e) {
                e = window.event || e;
                var target = e.srcElement || e.target,
                    pageNum = parseInt($(this).parent('li').index()) + 1;
                if (target.nodeName != "A" && flag == FINGER) {
                    doAction('report-history-detail-oa.html?flag='+ flag +'&page=' + pageNum + '&houseNum=' + me.props.houseNum, '报事详情')
                    // console.log('link')
                } else if (target.nodeName != "A" && !flag){
                    doAction('report-history-detail-oa.html?flag='+ flag +'&page=' + pageNum, '报事详情')
                }
            });

            //咨询点击运行
            $($consult).on('tap', function (e) {
                e = window.event || e;
                var target = e.srcElement || e.target;
                if (target.nodeName == "A") {
                    doAction('report-consult-oa.html?flag=finger&eventId=' + eventId, '报事咨询')
                }
            });

            //评价点击运行
            $($evaluation).on('tap', function (e) {
                e = window.event || e;
                var target = e.srcElement || e.target;
                if (target.nodeName == "A" && flag == FINGER) {
                    doAction('report-comment-oa.html?flag=finger&eventId=' + eventId + '&userId=' + staffId + '&wfOrderId=' + wfOrderId, '报事评价')
                } else if (target.nodeName == "A" && !flag) {
                    doAction('report-comment-oa.html?flag=&eventId=' + eventId + '&userId=' + staffId + '&wfOrderId=' + wfOrderId, '报事评价')
                }
            })

        },
        render: function () {
            var info = this.props.info,
                status = '',
                bgClass = '',
                btnStatue = 'ele-hide',
                publishTime = lf.utils.format(info.createTime, 'yyyy-MM-dd hh:mm');

            if (info.status == '0') {
                status = '待处理';
                bgClass = "orangeBg";
            }
            else if (info.status == '1') {
                status = '处理中';
                bgClass = "redBg"
            }
            else if (info.status == '2') {
                status = '已处理';
                bgClass = "greenBg"
            }
            else {
                status = '已完成';
                bgClass = "grayBg"
            }

            btnStatue = info.evaluate == 0 ? 'ele-hide' : '';

            return (
                <li className="mui-table-view-cell">
                    <div href="javascript:;" className="to-detail" ref="toDetail">
                        <div className="top">
                            <h4 className="mui-ellipsis title" ref="title">{info.title}</h4>
                            <span className="date">{publishTime}</span>
                        </div>
                        <div className="bottom">
                            <p className="mui-ellipsis statue">
                                <span className={'type ' + bgClass}>{status}</span>
                            </p>
                            <div className="link-btn">
                                {   flag == FINGER ?
                                    <a href="javascript:;" ref='consult'>咨询</a>
                                    : ''
                                }
                                <a href="javascript:;" className={btnStatue} ref="evaluation">评价</a>
                            </div>
                        </div>
                    </div>
                </li>
            )
        }
    })

    // <div className="mui-table-cell mui-col-xs-2 mui-text-right">
    //
    // </div>

    var Root = r.createClass({
        getInitialState: function () {
            return ({
                list: [],
                user: '',
                houseNum: '',
                page: '',
                noData: false
            })
        },
        getList: function (page,shouldAppend) {
            var me = this,
                api = '',
                data = '',
                user = me.props.user;

            if (!page) page = 1;

            me.setState({loadingStatus: 'block', page: page});

            if(flag == FINGER){
                data = {
                    projectId: user.projectId,
                    houseNum: me.state.houseNum,
                    phone: user.mobile,
                    page: page,
                }
                api = lf.finger.api.event.reportList;
            }else{
                data = {
                    page: page,
                    phone: user.phone||dataId.phone,
                }
                api = apiUrl + '/api/work/event/getEventReportList';//lf.api.report.history;
            };

            console.log(api)
            ajax({
                url: api,
                data: data,
                headers: {
                    openId: dataId.openId,
                },
                success: function (data) {
                    //成功
                    if (data.code == '200') {
                        console.log(data.dataList);

                        if (data.dataList.length == 0) {
                            me.setState({noData: true})
                        }

                        let resultList = data.dataList,
                            maxCount = data.maxCount,
                            appendedList;


                        if (shouldAppend) {
                            appendedList = me.state.list
                            // console.log(appendedList);
                            $.each(resultList, function (i, item) {
                                appendedList.push(item);
                            });

                            mui('#pullrefresh')
                                .pullRefresh()
                                .endPullupToRefresh((appendedList.length == maxCount)); //refresh completed

                            me.setState({
                                list: appendedList,
                                loadingStatus: 'none',
                                noData: false
                            });
                        }
                        else {
                            me.setState({
                                list: resultList,
                                loadingStatus: 'none',
                            });
                        }
                    }
                    else {
                        alert(data.desc);
                    }
                }
            });

        },
        componentWillMount: function () {

            var me= this,
                user = this.props.user;

            setTitle('报事列表');

            if(flag == FINGER){
                ajax({
                    type: "get",
                    data: {
                        houseId: user.houseId
                    },
                    success: function (data) {
                        // console.log(data);
                        //成功
                        if (data.code == '200') {
                            me.setState({houseNum: data.data.houseNum});
                            me.getList(1);
                        }
                        else {
                            alert(data.desc);
                        }
                    }

                }, lf.finger.api.household.getHouseInfo);
            }else{
                me.getList(1);
            }

            lf.appJs.refresh();

        },
        render: function () {
            return (
                <div className="report-history-list container">
                    <NoticeList info={this.state.list} user={this.state.user} noData={this.state.noData}
                                page={this.props.page} houseNum={this.state.houseNum}/>
                </div>
            )
        },
        componentWillReceiveProps: function (nextProps) {
            var page = nextProps.page;
            this.getList(page, true)
        }
    });


    // r.render(
    //     <PullRefresh data={<Container />}/>,
    //     // <Container />,
    //     document.getElementById('root'), function () {
    //         $('#root').css('background','none');
    //     }
    // )

    var PullRefreshCon = React.createClass({
        getInitialState: function () {
            return {
                page: 1,
            }
        },
        componentWillMount: function () {

        },
        pullupFn: function () {
            var newPage = ++this.state.page;
            this.setState({page: newPage});
        },
        render: function () {
            var me = this;
            // console.log(me.state);
            return <PullRefresh pullupFn={me.pullupFn} data={<Root user={me.props.user} page={me.state.page}/>}/>;
        }
    });
    lf.bridgeJs.getUser(function(user) {
        ajax({
            url: apiUrl + api.getGlobalId,
            type: 'post',
            data: {
                custGlobalId: user.globalId||user.custLoginVo.globalId,//user.id,'C1606281657108af41b8e068927' ||
            },
            success: function (data) {
                dataId = data.data;
                r.render(
                    <PullRefreshCon user={user} />,
                    document.getElementById('root'), function () {
                        $('#root').css('background', '#ededed');
                        $('.mui-scroll').css('background', '#ededed');
                    }
                )
            }
        })
    })

})(liefeng, React);
